extends Area2D

signal collected(heal_amount)

@export var heal_amount: int = 20  # 恢复的生命值
@export var collect_sound: AudioStream  # 收集音效

var velocity = Vector2.ZERO
var is_being_collected = false

func _ready():
	# 设置收集音效
	if collect_sound:
		$AudioStreamPlayer.stream = collect_sound

# 弹出效果，用于从宝箱中弹出
func pop_out(initial_velocity = Vector2.ZERO):
	velocity = initial_velocity
	
	# 应用初始速度
	position += velocity * 0.1
	
	# 创建一个缓动效果，让药水变大再恢复正常大小
	var tween = create_tween()
	tween.tween_property(self, "scale", Vector2(1.5, 1.5), 0.1)
	tween.tween_property(self, "scale", Vector2(1.0, 1.0), 0.2)
	
	# 应用闪光效果
	var glow_tween = create_tween()
	glow_tween.tween_property(self, "modulate", Color(1.5, 1.5, 1.5), 0.2)
	glow_tween.tween_property(self, "modulate", Color(1, 1, 1), 0.3)

func collect():
	if is_being_collected:
		return
	
	is_being_collected = true
	
	# 禁用碰撞
	$CollisionShape2D.set_deferred("disabled", true)
	
	# 播放收集音效
	if $AudioStreamPlayer.stream:
		$AudioStreamPlayer.play()
	
	# 发送收集信号
	emit_signal("collected", heal_amount)
	
	# 创建收集动画
	var tween = create_tween()
	tween.tween_property(self, "scale", Vector2(1.5, 1.5), 0.1)
	tween.tween_property(self, "scale", Vector2(0, 0), 0.2)
	tween.tween_callback(queue_free)
	
	# 创建粒子效果（如果有粒子系统）
	# if has_node("Particles2D"):
	# 	$Particles2D.emitting = true

func _on_body_entered(body):
	# 检查碰撞的是否为玩家
	if body.is_in_group("player"):
		collect()
		
		# 如果玩家有heal方法，调用它
		if body.has_method("heal"):
			body.heal(heal_amount)
		# 或者尝试通过stats对象调用
		elif body.has_method("get_stats"):
			var stats = body.get_stats()
			if stats and stats.has_method("heal"):
				stats.heal(heal_amount) 
